import { http } from './http';

// 用户相关接口
export interface User {
  id: string;
  username: string;
  email: string;
  avatar?: string;
  createdAt: string;
  updatedAt: string;
}

export interface LoginRequest {
  username: string;
  password: string;
}

export interface LoginResponse {
  token: string;
  user: User;
  expiresIn: number;
}

export interface RegisterRequest {
  username: string;
  email: string;
  password: string;
  confirmPassword: string;
}

// 视频相关接口
export interface Video {
  id: string;
  title: string;
  description?: string;
  thumbnail: string;
  duration: string;
  views: string;
  uploader: string;
  uploadTime: string;
  url?: string;
  tags?: string[];
  category?: string;
}

export interface VideoListParams {
  page?: number;
  pageSize?: number;
  category?: string;
  keyword?: string;
  sortBy?: 'latest' | 'popular' | 'views';
}

export interface VideoListResponse {
  videos: Video[];
  total: number;
  page: number;
  pageSize: number;
  totalPages: number;
}

// API服务类
class ApiService {
  // ==================== 用户相关 ====================
  
  // 用户登录
  async login(data: LoginRequest): Promise<LoginResponse> {
    const response = await http.post<LoginResponse>('/auth/login', data);
    
    // 登录成功后保存token
    if (response.token) {
      http.setToken(response.token, true); // 持久化保存
    }
    
    return response;
  }

  // 用户注册
  async register(data: RegisterRequest): Promise<User> {
    return await http.post<User>('/auth/register', data);
  }

  // 用户登出
  async logout(): Promise<void> {
    await http.post('/auth/logout');
    http.clearToken();
  }

  // 获取当前用户信息
  async getCurrentUser(): Promise<User> {
    return await http.get<User>('/auth/me');
  }

  // 更新用户信息
  async updateUser(data: Partial<User>): Promise<User> {
    return await http.put<User>('/users/profile', data);
  }

  // 上传头像
  async uploadAvatar(file: File): Promise<{ url: string }> {
    return await http.upload<{ url: string }>('/users/avatar', file);
  }

  // ==================== 视频相关 ====================

  // 获取视频列表
  async getVideoList(params?: VideoListParams): Promise<VideoListResponse> {
    return await http.get<VideoListResponse>('/videos', { params });
  }

  // 获取视频详情
  async getVideoDetail(id: string): Promise<Video> {
    return await http.get<Video>(`/videos/${id}`);
  }

  // 搜索视频
  async searchVideos(keyword: string, params?: Omit<VideoListParams, 'keyword'>): Promise<VideoListResponse> {
    return await http.get<VideoListResponse>('/videos/search', {
      params: { keyword, ...params }
    });
  }

  // 获取热门视频
  async getPopularVideos(limit: number = 10): Promise<Video[]> {
    return await http.get<Video[]>('/videos/popular', { params: { limit } });
  }

  // 获取最新视频
  async getLatestVideos(limit: number = 10): Promise<Video[]> {
    return await http.get<Video[]>('/videos/latest', { params: { limit } });
  }

  // 按分类获取视频
  async getVideosByCategory(category: string, params?: VideoListParams): Promise<VideoListResponse> {
    return await http.get<VideoListResponse>(`/videos/category/${category}`, { params });
  }

  // 上传视频
  async uploadVideo(file: File, metadata: Partial<Video>): Promise<Video> {
    // 先上传文件
    const uploadResult = await http.upload<{ url: string }>('/videos/upload', file);
    
    // 然后创建视频记录
    return await http.post<Video>('/videos', {
      ...metadata,
      url: uploadResult.url
    });
  }

  // 更新视频信息
  async updateVideo(id: string, data: Partial<Video>): Promise<Video> {
    return await http.put<Video>(`/videos/${id}`, data);
  }

  // 删除视频
  async deleteVideo(id: string): Promise<void> {
    await http.delete(`/videos/${id}`);
  }

  // ==================== 其他功能 ====================

  // 获取分类列表
  async getCategories(): Promise<string[]> {
    return await http.get<string[]>('/categories');
  }

  // 获取统计信息
  async getStats(): Promise<{
    totalVideos: number;
    totalUsers: number;
    totalViews: number;
  }> {
    return await http.get('/stats');
  }

  // 健康检查
  async healthCheck(): Promise<{ status: string; timestamp: string }> {
    return await http.get('/health');
  }
}

// 创建并导出API服务实例
export const api = new ApiService();

// 导出类型
export type {
  User,
  LoginRequest,
  LoginResponse,
  RegisterRequest,
  Video,
  VideoListParams,
  VideoListResponse,
};
